<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/1 0001
 * Time: 10:01
 */

namespace app\components;


class RedisHelper
{
    //处理yii-redis 使用hgetall返回的数据
    public static function dealHgetall(array $ary, $callback = null)
    {
        $result = [];
        for ($i = 0; $i < count($ary); $i += 2) {
            if ($callback instanceof \Closure) {
                $result[$ary[$i]] = $callback($ary[$i + 1]);
            } else if ($callback && is_string($callback)) {
                $result[$ary[$i]] = call_user_func($callback, $ary[$i + 1]);
            } else {
                $result[$ary[$i]] = $ary[$i + 1];
            }
        }
        return $result;
    }

    /**
     * @desc 迭代式的删除redis key
     * 用法:
     * $redis = BaseService::S()->getRedisConfig(\Yii::$app->redis2);
     * RedisHelper::delByScan(['mindCard'], $redis);
     * @author yanglb@immatchu.com
     * @created time 2018-12-29
     * @param object $redisInstance redis数据库实例
     * @param array $matchGroup 要删除的key(可以是key的前缀)所组成的数组
     * @param int $count 一次最多删除多少条key
     * @return bool
     */
    public static function delByScan($redisInstance, array $matchGroup = [], $count = 1000)
    {
        if (empty($matchGroup)) {
            return false;
        }
        $redis = $redisInstance;
        $it = null;
        do {
            $arr_keys = $redis->scan($it, null, $count);
            if (is_array($arr_keys) && count($arr_keys) > 0) {
                foreach ($arr_keys as $key) {
                    foreach ($matchGroup as $match) {
                        if (strpos($key, $match) !== false) {
                            $redis->del($key);
                        }
                    }
                }
            }
        } while ($it > 0);
        return true;
    }
}